import { reqGetCode, reqRegister, reqLogin, reqGetUserInfo, reqLogout } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/useToken'
const state = {
    code: '',
    token: getToken(),
    userInfo: {}
}

const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    LOGOUT(state) {
        state.token = ''
        state.userInfo = {}
        removeToken()
    }
}

const actions = {
    async getCode({ commit }, phone) {
        const res = await reqGetCode()
        console.log(res)
        if (res.code == 200) {
            commit('GETCODE', res.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    async register({ commit }, userInfo) {
        const res = await reqRegister(userInfo)
        console.log(res)
        if (res.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    async userLogin({ commit }, userInfo) {
        const res = await reqLogin(userInfo);
        console.log(res)
        if (res.code == 200) {
            commit('USERLOGIN', res.data.token)
            // 持久化存储token
            setToken(res.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    async getUserInfo({ commit }) {
        const res = await reqGetUserInfo()
        if (res.code == 200) {
            commit("GETUSERINFO", res.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    async logout({ commit }) {
        const res = await reqLogout()
        if (res.code == 200) {
            commit('LOGOUT')
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }
}

const getters = {

}

export default {
    state,
    mutations,
    actions,
    getters
}